package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author fengzhu
 * @since 2024-10-10
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 展示购物车的内容
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        List<ShoppingCart> list =shoppingCartService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 从会话中拿取到
     * @param request
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<String> add(HttpServletRequest request, @RequestBody ShoppingCart shoppingCart) {
        // 从会话中获取用户 ID
        Long userId = (Long) request.getSession().getAttribute("user");

        // 检查用户是否已登录
        if (userId == null) {
            return R.error("用户未登录");
        }

        shoppingCart.setUserId(userId); // 设置用户 ID
        shoppingCartService.save(shoppingCart); // 保存购物车项

        return R.success("添加成功");
    }

    /**
     *实现购物车的清空功能
     * @param request
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(HttpServletRequest request) {
        Long userId =(Long)request.getSession().getAttribute("user");
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(queryWrapper);
        return R.success("成功");
    }

    @PostMapping("/sub")
    public R<String> sub(HttpServletRequest request, @RequestParam(required = false) List<Long> dishId, @RequestParam(required = false) List<Long> setmealId) {
        Long userId = (Long) request.getSession().getAttribute("user");

        // 创建查询条件
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);

        // 如果 dishId 不为空，添加对应的查询条件
        if (dishId != null && !dishId.isEmpty()) {
            queryWrapper.in(ShoppingCart::getDishId, dishId);
        }

        // 如果 setmealId 不为空，添加对应的查询条件
        if (setmealId != null && !setmealId.isEmpty()) {
            queryWrapper.in(ShoppingCart::getSetmealId, setmealId);
        }

        // 根据查询条件移除购物车中的对应项
        shoppingCartService.remove(queryWrapper);

        return R.success("成功");
    }


}
